package zhuyun.code.launcheractivity.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.io.FileOutputStream
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.ceil

/**
 * @author: Administrator
 * @date: 2021/11/30
 */
object CommonUtils {
    fun saveImageToGallery(context: Context, bmp:Bitmap):Boolean{
        val appDir = File(Environment.getExternalStorageDirectory(),"download")
        if(!appDir.exists()){
            appDir.mkdir()
        }
        val fileName = "${System.currentTimeMillis()}.jpg"
        val file = File(appDir,fileName)
        val fos = FileOutputStream(file)
        val isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG,100,fos)
        fos.flush()
        fos.close()
        MediaStore.Images.Media.insertImage(context.contentResolver,file.absolutePath,fileName,null)
        val uri = Uri.fromFile(file)
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri))
        return isSuccess
    }

    fun getStandardDate(originalTime:String):String{
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val date = sdf.parse(originalTime)
        var standardDate:String=""
        val timeOfMills = date.time
        val sdf2 = SimpleDateFormat("MM-dd HH:mm")
        val formatTime = sdf2.format(date)
        val timeInterval = System.currentTimeMillis() - timeOfMills
        val seconds = ceil(timeInterval/1000.0).toLong()
        val minutes = ceil(timeInterval/60/1000.0).toLong()
        val hours = ceil(timeInterval/60/60/1000.0).toLong()
        val days = ceil(timeInterval/60/60/24/1000.0).toLong()
        if(days>4){
            standardDate = formatTime
        } else if(days>1){
            standardDate = "${days}天前"
        } else if(hours>1){
            if(hours>24){
                standardDate = "1天前"
            } else if(hours>1){
                standardDate = "${hours}小时前"
            }
        } else if(minutes>1){
            if(minutes == 60L){
                standardDate = "1小时前"
            } else if(minutes>1){
                standardDate = "${minutes}分钟前"
            }
        } else if(seconds>1){
            if(seconds == 60L){
                standardDate = "1分钟前"
            } else if(seconds>1){
                standardDate = "${seconds}秒前"
            }
        } else{
            standardDate = "刚刚"
        }
        return standardDate
    }


}